package com.wang.common.servlet;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


import com.wang.common.pojo.ApiResponse;
import com.wang.common.pojo.ApiResponseEnum;
import com.wang.common.util.ConstatFinalUtil;
import com.wang.users.pojo.AAdmins;
import com.wang.users.pojo.AAdminsEnum;
import com.wang.users.pojo.AUsers;
import com.wang.users.pojo.AUsersEnum;
import com.wang.users.service.IUsersDbService;
import com.wang.users.service.impl.UsersDbServiceImpl;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

/**
 * ~Servlet开发分三步走: 写一个java代码,Servlet 配置web.xml 在浏览器中访问
 * <p>
 * ~初始化,Service,一个销毁
 *
 * @author wangshMac
 */
@WebServlet(urlPatterns = "/NoLoginServlet")
public class NoLoginServlet extends BaseServlet {
    private IUsersDbService usersDbService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        this.usersDbService = new UsersDbServiceImpl();
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /* 接收参数 */
        String method = request.getParameter("method");
        if ("adminsLogin".equalsIgnoreCase(method)) {
            /* 打开管理员登陆页面 */
            adminsLogin(request, response);
        } else if ("adminsLoginSubmit".equalsIgnoreCase(method)) {
            /* 提交管理员登陆 */
            adminsLoginSubmit(request, response);
        } else if ("login".equalsIgnoreCase(method)) {
            /* 打开用户登陆页面 */
            login(request, response);
        } else if ("loginSubmit".equalsIgnoreCase(method)) {
            /* 提交用户登陆 */
            loginSubmit(request, response);
        } else if ("register".equalsIgnoreCase(method)) {
            /* 打开用户注册页面 */
            register(request, response);
        } else if ("registerSubmit".equalsIgnoreCase(method)) {
            /* 提交用户注册 */
            registerSubmit(request, response);
        }
    }

    /**
     * 注册提交操作
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void registerSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        /* 存储多个结果,Map存储 */
        Map<String, Object> dataMapJava = new HashMap<String, Object>();
        apiResponse.setDataMapJava(dataMapJava);

        HttpSession session = request.getSession();

        /* 接收参数 */
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String rand = request.getParameter("rand");

        /* session中获取验证码 */
        String randSess = (String) session.getAttribute("randSess");

        if (this.regexUtil.verifyCode(randSess, rand)) {
            AUsers users = new AUsers();

            users.setEmail(email);
            users.setPassword(password);

            users.setStatus(AUsersEnum.STATUS_ENABLE.getStatus());

            ApiResponse<Object> apiResponseDb = this.usersDbService.saveOneUsersService(users);

            /* 设置数据库的保存信息 */
            apiResponse.setCode(apiResponseDb.getCode());
        } else {
            /* 验证码不正确 */
            apiResponse.setCode(ApiResponseEnum.INFO_VERIFY_CODE_INCORR.getStatus());
        }

        apiResponse.setInfo(
                ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
                Collections.EMPTY_MAP);

        request.setAttribute("response", apiResponse.toJSON());
        this.register(request, response);
    }

    /**
     * 打开注册页面
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void register(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        /* 准备路径 */
        this.path = "/WEB-INF/jsp/head/register.jsp";
        /* 页面跳转 */
        request.getRequestDispatcher(path).forward(request, response);
    }

    /**
     * 登陆提交操作
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void loginSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        /* 存储多个结果,Map存储 */
        Map<String, Object> dataMapJava = new HashMap<String, Object>();
        apiResponse.setDataMapJava(dataMapJava);

        HttpSession session = request.getSession();

        /* 接收参数 */
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String rand = request.getParameter("rand");

        /* session中获取验证码 */
        String randSess = (String) session.getAttribute("randSess");

        if (this.regexUtil.verifyCode(randSess, rand)) {
            /* 验证码正确 */
            /* 查询db,处理业务逻辑 */
            Map<String, Object> condMap = new HashMap<String, Object>();
            condMap.put("email", email);
            ApiResponse<AUsers> apiRes = this.usersDbService.findOneUsersService(condMap);
            AUsers users = apiRes.getDataOneJava();
            /* 检验邮箱 */
            if (users != null) {
                /* 将邮箱放到request中 */
                dataMapJava.put("email", users.getEmail());
                /* 检验密码 */
                if (this.encryptUtil.checkStr(password, users.getPassword())) {
                    /* 状态必须为启用 */
                    if (users.getStatus() == AAdminsEnum.STATUS_ENABLE.getStatus()) {
                        session.setAttribute("users", users);
                        session.setAttribute("lastLoginTime", users.getLastLoginTime());

                        /* 登陆成功 */
                        users.setLastLoginTime(new Date());

                        this.usersDbService.updateOneUsersService(users);

                        /* 说明已经登陆 */
                        response.sendRedirect(request.getContextPath() + "/back/UsersBackServlet?method=main");
                        return;
                    } else {
                        /* 状态为禁用 */
                        apiResponse.setCode(ApiResponseEnum.INFO_ACCOUNT_DISABLED.getStatus());
                    }
                } else {
                    apiResponse.setCode(ApiResponseEnum.INFO_PASS_INCORRECT.getStatus());
                }
            } else {
                /* 邮箱不存在 */
                apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_NOT_EXISTS.getStatus());
            }
        } else {
            /* 验证码不正确 */
            apiResponse.setCode(ApiResponseEnum.INFO_VERIFY_CODE_INCORR.getStatus());
        }

        apiResponse.setInfo(
                ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
                Collections.EMPTY_MAP);

        this.updateFlag = "true";
        request.setAttribute("response", apiResponse.toJSON());
        this.login(request, response);
    }

    /**
     * 打开登陆页面
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        /* 准备路径 */
        this.path = "/WEB-INF/jsp/back/login.jsp";
        /* 从session获取信息 */
        AUsers users = (AUsers) this.findObjfromSession(request, "users");
        if (users != null) {
            /* 说明已经登陆 */
            response.sendRedirect(request.getContextPath() + "/head/UsersHeadServlet?method=main");
            return;
        }
        /* 页面跳转 */
        request.getRequestDispatcher(path).forward(request, response);
    }

    /**
     * 提交管理员登陆
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void adminsLoginSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        /* 存储多个结果,Map存储 */
        Map<String, Object> dataMapJava = new HashMap<String, Object>();
        apiResponse.setDataMapJava(dataMapJava);

        HttpSession session = request.getSession();

        /* 接收参数 */
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String rand = request.getParameter("rand");

        /* session中获取验证码 */
        String randSess = (String) session.getAttribute("randSess");

        if (this.regexUtil.verifyCode(randSess, rand)) {
            /* 验证码正确 */
            /* 查询db,处理业务逻辑 */
            Map<String, Object> condMap = new HashMap<String, Object>();
            condMap.put("email", email);
            ApiResponse<AAdmins> apiRes = this.usersDbService.findOneAdminsService(condMap);
            AAdmins admins = apiRes.getDataOneJava();
            /* 检验邮箱 */
            if (admins != null) {
                /* 将邮箱放到request中 */
                dataMapJava.put("email", admins.getEmail());
                /* 检验密码 */
                if (this.encryptUtil.checkStr(password, admins.getPassword())) {
                    /* 状态必须为启用 */
                    if (admins.getStatus() == AAdminsEnum.STATUS_ENABLE.getStatus()) {
                        session.setAttribute("admins", admins);
                        session.setAttribute("lastLoginTime", admins.getLastLoginTime());

                        /* 登陆成功 */
                        admins.setLastLoginTime(new Date());

                        this.usersDbService.updateOneAdminsService(admins);

                        /* 说明已经登陆 */
                        response.sendRedirect(request.getContextPath() + "/back/AdminsBackServlet?method=main");
                        return;
                    } else {
                        /* 状态为禁用 */
                        apiResponse.setCode(ApiResponseEnum.INFO_ACCOUNT_DISABLED.getStatus());
                    }
                } else {
                    apiResponse.setCode(ApiResponseEnum.INFO_PASS_INCORRECT.getStatus());
                }
            } else {
                /* 邮箱不存在 */
                apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_NOT_EXISTS.getStatus());
            }
        } else {
            /* 验证码不正确 */
            apiResponse.setCode(ApiResponseEnum.INFO_VERIFY_CODE_INCORR.getStatus());
        }

        apiResponse.setInfo(
                ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
                Collections.EMPTY_MAP);

        request.setAttribute("response", apiResponse.toJSON());
        this.adminsLogin(request, response);
    }

    /**
     * 打开管理员登陆页面
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void adminsLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* 准备路径 */
        this.path = "/WEB-INF/jsp/back/login.jsp";
        /* 从session获取信息 */
        AAdmins admins = (AAdmins) this.findObjfromSession(request, "admins");
        if (admins != null) {
            /* 说明已经登陆 */
            response.sendRedirect(request.getContextPath() + "/back/AdminsBackServlet?method=main");
            return;
        }
        /* 页面跳转 */
        request.getRequestDispatcher(path).forward(request, response);
    }
}
